import { Controller, Param, Post, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import { TestService } from './test.service';
import { FileService } from '@app/file';
import { MakeAuthPowerGuard, UPDATE_POWER } from 'src/auth/auth.guard';
import { FileInterceptor } from '@nestjs/platform-express';
import { PrismaService } from '@app/prisma';
import { ForbiddenError } from '@nestjs/apollo';

export const TestGuard = MakeAuthPowerGuard("/test", "模拟测试")
@Controller('test')
export class TestController {
  constructor(
    private readonly service: TestService,
    private readonly file: FileService,
    private readonly prisma: PrismaService
  ) { }


  @Post(":id/:name/upload")
  @UseGuards(TestGuard([UPDATE_POWER]))
  @UseInterceptors(FileInterceptor("file"))
  async uploadResource(
    @Param("id") id: number,
    @Param("name") name: string,
    @UploadedFile() file: Express.Multer.File
  ) {
    id *= 1
    const buffer = file.buffer
    const entity = await this.prisma.sys_test_chapter.findUnique({ where: { id } });
    if (!entity) throw new ForbiddenError("章节不存在")
    this.file.writeFile(this.service.getChapterResource(entity, name), buffer)
    return entity
  }
}
